<template>
  <div class="onerow">
    <div class="col-4">
      <h3>组件配置页面展示</h3>
      <div class="draggable" style="padding: 20px"  >
      <div class="Grid" style="padding: 20px;border: 2px dashed #100;" >
       <div class="Row" :rowId="row.rowId"  @contextmenu="showRowMenu(row.rowId)" v-for="(row,rowId) in rowList" :key="rowId" >
        <div class="Grid-cell" :type="item.type" :id="item.id" draggable="true" v-for="(item,d) in row" :key="d" @dblclick="editProperties(item.id)">
		  <PublicLabel :item="item" />
		  <PublicItem :item="item" :design="isdesign" /> 	  
        </div>
		 <vue-context-menu :contextMenuData="rowMenuData"
        @beforeaddrow="beforeaddrow()"
        @afteraddrow="afteraddrow()"
		@deleterow="deleterow()"
		@prevView="prevView()"
		></vue-context-menu> 
      </div> 
   </div>
	</div>
    </div>
    <div class="col-5">
      <h3>可用组件列表</h3>
	    <div
        class="list-group"    >
	    <div class="list-group-item" v-for="element in list1" :key="element.id">
        <div class="Grid-cell" draggable="true" :type="element.type" >
		<PublicItem :item="element" :design="isdesign"  />
		</div>
		</div>
	  </div>
    </div>
	<CtrlProperty  :projectParameters="editPropertyTemplate" :QualityDialogFlag.sync="QualityDialogFlag" @okEvent="changedProperties" />
  </div>
</template>
<script>
 import PublicItem from "../PublicItem/index";
 import PublicLabel from "../PublicLabel/index";
 import CtrlProperty from "../CtrlProperty/index";
 import storage from 'good-storage';
//let canva;
//let cansText;
let useComponents;
let targetComponents;
export default {
  name: "clone",
  display: "Clone",
  order: 2,
  mounted() {
    this.initDrag()
  },
  components: {
    PublicItem,
	PublicLabel,
	CtrlProperty
  },
  data() {
    return {
	   isdesign:1,
       rowList:[],
	   rowList1: [[{type:"input",model:"name",label:"姓名",options:{width:"80px;",placeholder:"请输入内容"}},
	  {type:"input",model:"test",label:"测试",options:{width:"80px;",placeholder:"请输入测试内容"}}
	  ],[{type:"input-number" ,model:"age",label:"年龄",options:{width:"80px;",placeholder:"输入描述文字","min":1,"max":10}}],
	  [{type:"select",model:"hobby",label:"爱好",options:{width:"80px;",placeholder:"请选择",
	  items: [
        {
          value: "选项1",
          label: "黄金糕"
        },
        {
          value: "选项2",
          label: "双皮奶"
        },
        {
          value: "选项3",
          label: "蚵仔煎"
        },
        {
          value: "选项4",
          label: "龙须面"
        },
        {
          value: "选项5",
          label: "北京烤鸭"
        }
      ]
	  }},{type:"switch",model:"sex",label:"性别",options:{width:"80px;",activeColor:"#13ce66", inactiveColor:"#ff4949"}}]
	  ],
	         list1: [
      {type:"input",label:"输入框",options:{width:"80px;",placeholder:"请输入内容"}}
	  ,{type:"input-number" ,label:"计数器",options:{width:"80px;",placeholder:"输入描述文字","min":1,"max":10}},
	  {type:"select",model:"hobby",label:"选择器",options:{width:"80px;",placeholder:"请选择",
	  items: [
        {
          value: "1",
          label: "选项1"
        },
        {
          value: "2",
          label: "选项2"
        },
        {
          value: "3",
          label: "选项3"
        },
        {
          value: "4",
          label: "选项4"
        }
      ]
	  }},{type:"switch",label:"开关",options:{width:"80px;",activeColor:"#13ce66", inactiveColor:"#ff4949"}}
      ],
	  //是否为移动对象
	  move:false,
	  // 菜单数据
      rowMenuData: {
         menuName: 'rowManager',
         //菜单显示的位置
         axis: {
           x: null,
           y: null
         },
         //菜单选项
         menulists: [{
           fnHandler: 'beforeaddrow', //绑定事件
           icoName: 'fa fa-home fa-fw', //icon图标
           btnName: '前面插入行' //菜单名称
         }, {
             fnHandler: 'afteraddrow',
             icoName: 'fa fa-minus-square-o  fa-fw',
             btnName: '后面插入行'
         },{
             fnHandler: 'deleterow',
             icoName: 'fa fa-minus-square-o  fa-fw',
             btnName: '删除行'
         },
		 {
             fnHandler: 'prevView',
             icoName: 'fa fa-minus-square-o  fa-fw',
             btnName: '预览'
         }
		 ]
       },
	   menuRowId:'',
	   propertyTemplate:[
	   {"ctrlType":"input","id":"",ctrlProperties:[
	   [{type:"input",model:"modelname","value":"",label:"属性名称",options:{width:"80px;",placeholder:"请输入属性名称"}}],
	   [{type:"input",model:"title","value":"",label:"标题",options:{width:"80px;",placeholder:"请输入属性标题"}}],
	   [{type:"input",model:"width","value":"",label:"宽度",options:{width:"80px;",placeholder:"请输入属性宽度"}}],
	   [{type:"input",model:"placeholder","value":"",label:"未输入时提示文字",options:{width:"80px;",placeholder:"请输入属性提示信息"}}]
	   ]
	   }
	   ],
	   QualityDialogFlag:false,
	   editPropertyTemplate:{},
	   
    }
  },
  methods: {
   initDrag() {
      useComponents = document.getElementsByClassName('list-group')[0];
      targetComponents = document.getElementsByClassName('Grid')[0];
      useComponents.ondragstart=this.dragstart;
	  useComponents.ondrag = this.drag;
	  useComponents.ondragend= this.dragend;
	  useComponents.ondrop= this.useComponentDrop;
	  useComponents.ondragenter=this.dragenter;
	  useComponents.ondragover= this.dragover;
	  useComponents.ondragleave= this.dragleave;
	  targetComponents.ondragstart=this.targetDragstart;
	  targetComponents.ondragenter=this.dragenter;
	  targetComponents.ondragover= this.dragover;
	  targetComponents.ondragleave= this.dragleave;
	  targetComponents.ondrop= this.drop;
    },
    dragstart(e) {
	    //debugger;
		this.move = false;
        console.log('dragstart:'+JSON.stringify(e.target));
        e.dataTransfer.setData('type',e.target.getAttribute("type"));
    }, 
    targetDragstart(e) {
	    debugger;
		this.move = true;
        console.log('dragstart:'+JSON.stringify(e.target));
        e.dataTransfer.setData('id',e.target.getAttribute("id"));
    },
     drag(e) {
        console.log('drag',e.target.id);
    },
     dragend(e) {
        console.log('dragend'+e)
    },
     dragenter (e) {
        console.log('dragenter');
        e.preventDefault();
    },
     dragover(e) {
        console.log('dragover');
        e.preventDefault();
        //drop.innerHTML = '';
    },
     dragleave(e) {
        console.log('dragleave');
        e.preventDefault();
    },
	useComponentDrop(e){
	 console.log('useComponentDrop e:'+e);
	 var id = e.dataTransfer.getData('id');
	 this.removeNowObj(id);
	},
     drop(e) {
	    //
        console.log('drop');
		debugger;
        var type = e.dataTransfer.getData('type');
		var id = e.dataTransfer.getData('id');
        console.log('type:'+type);
        console.log('e.target._prevClass:'+e.target._prevClass);//Grid,Row,Grid-cell,undefined,
		console.log('e.target.parentNode._prevClass:'+e.target.parentNode._prevClass);
		//插入对象
		if(this.move){
		    this.insertMoveObject(e,id);
		}else{
 	   		this.insertObject(e,type);
        }       
	   e.preventDefault();
	   e.stopPropagation();
	},
   getTop(e) {
		var offset = e.offsetTop;
		if (e.offsetParent != null) offset += this.getTop(e.offsetParent);
		return offset;
  },
 getLeft(e) {
	if(e!=null){
	 var offset = e.offsetLeft;
	 if (e.offsetParent != null) offset += this.getLeft(e.offsetParent);
	 return offset;
	}
  },
  //插入对象
  insertObject(e,type){
     //判断目标对象类型
	 var prevClass = e.target._prevClass;
	 //根据type查询对象
     var dragObj ;
	 dragObj = this.findDragObj(type);
	 var cloneObj = JSON.parse(JSON.stringify(dragObj));
	 //设置对象id
	 cloneObj["id"]=this.uuid();
	 var objId;
	 if(prevClass=='Grid'){
	    //直接后面添加行
		var row=[];
	    row["rowId"]=this.uuid();
	    this.rowList.push(row);
		if(cloneObj){
		    row.push(cloneObj);
		}
	 }else if(prevClass=='Row'){
	    //直接加入行后面
		var rowId ;
		rowId = e.target.getAttribute("rowId");
		var rowObj= this.findRowById(rowId);
		if(rowObj&& cloneObj){
		    rowObj.push(cloneObj);
		}
	 }else if(prevClass=='Grid-cell'){
	    //插入对象前面		
        objId = e.target.getAttribute("id");
        this.insertObjectBeforce(objId,cloneObj);		
	 }else {
		//递归查询上级，直到是Grid-cell
		var e1;
		e1 = this.recursionFindGridCell(e);
		if(e1){
			//插入对象前面
			objId = e1.getAttribute("id");
			this.insertObjectBeforce(objId,cloneObj);
		}
	 }
  },
  //插入移动对象
  insertMoveObject(e,id){
     //判断目标对象类型
	 var prevClass = e.target._prevClass;
	 //根据type查询对象
     var dragObj ;
	 dragObj = this.findNowObj(id);
	 var cloneObj = JSON.parse(JSON.stringify(dragObj));
	 //删除现有对象
	 this.removeNowObj(cloneObj["id"]);
	 var objId;
	 if(prevClass=='Grid'){
	    //直接后面添加行
		var row=[];
	    row["rowId"]=this.uuid();
	    this.rowList.push(row);
		if(cloneObj){
		    row.push(cloneObj);
		}
	 }else if(prevClass=='Row'){
	    //直接加入行后面
		var rowId ;
		rowId = e.target.getAttribute("rowId");
		var rowObj= this.findRowById(rowId);
		if(rowObj&& cloneObj){
		    rowObj.push(cloneObj);
		}
	 }else if(prevClass=='Grid-cell'){
	    //插入对象前面		
        objId = e.target.getAttribute("id");
        this.insertObjectBeforce(objId,cloneObj);		
	 }else {
	    //递归查询上级，直到是Grid-cell
		var e1;
		e1 = this.recursionFindGridCell(e.target);
		if(e1){
			//插入对象前面
			objId = e1.getAttribute("id");
			this.insertObjectBeforce(objId,cloneObj);
		}
	 }
  },
  //递归查询上级，直到是Grid-cell
  recursionFindGridCell(e){
     if(e){
	    if(e){
	     var prevClass = e._prevClass;
		 if(prevClass=='Grid-cell'){
		   return e;
		 }else {
		  return this.recursionFindGridCell(e.parentElement);
		 }
		}else{
		  debugger;
		}
	 }
	 return null;
  },
  //在指定对象之前插入对象
  insertObjectBeforce(objId,insertObj){
      var i;
      for (i = 0; i < this.rowList.length; i++) {
			var rowObj = this.rowList[i];
			var j;
			for(j=0;j<rowObj.length;j++){
				if(rowObj[j].id == objId){
				    rowObj.splice(j,0,insertObj);
					return;
				}
			}
	  }
  },
  //根据rowId查询行对象
  findRowById(rowId){
	  var i;
      for (i = 0; i < this.rowList.length; i++) {
	     if(rowId == this.rowList[i].rowId){
			return this.rowList[i];
		 }
	  }
	  return null;
  },
  //根据type查询可用组件
  findDragObj(type){
      var i;
      for (i = 0; i < this.list1.length; i++) {
	    if(type==this.list1[i].type){
		  return this.list1[i];
		}
	  }
	  return null;
  },
  //根据id删除现有组件
  removeNowObj(id){
      var i;
      for (i = 0; i < this.rowList.length; i++) {
			var rowObj = this.rowList[i];
			var j;
			for(j=0;j<rowObj.length;j++){
				if(rowObj[j].id == id){
					rowObj.splice(j,1);
					return;
				}
			}
	  }
  },
  //根据id查询现有组件
  findNowObj(id){
      var i;
      for (i = 0; i < this.rowList.length; i++) {
			var rowObj = this.rowList[i];
			var j;
			for(j=0;j<rowObj.length;j++){
				if(rowObj[j].id == id){
					return rowObj[j];
				}
			}
	  }
	  return null;
  },
  //uuid
	uuid() {
		var s = [];
		var hexDigits = '0123456789abcdef';
		for (var i = 0; i < 36; i++) {
			s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = '4';
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
		s[8] = s[13] = s[18] = s[23] = '-';
		this.uuidA = s.join('');
		//console.log(s.join(''), 's.join("")');
		return this.uuidA;
    },
	showRowMenu (rowId) {
	    console.log('rowid:'+rowId);
        event.preventDefault()
        var x = event.clientX
        var y = event.clientY
        // Get the current location
      this.rowMenuData.axis = {
        x, y
      }
	  this.menuRowId = rowId;
    },
    beforeaddrow () {
	  var i; 
	  var rowId = this.menuRowId; 
      for (i = 0; i < this.rowList.length; i++) {
	     if(rowId== this.rowList[i].rowId){
		   var row =[];  
		   row["rowId"]=this.uuid();
		   this.rowList.splice(i,0,row);
		   break;
		 }
	  }
      console.log('beforeaddrow rowId:'+rowId);
    },
    deleterow () {
	   var rowId = this.menuRowId;
      console.log('deleterow rowId:'+rowId);
	  var i;
      for (i = 0; i < this.rowList.length; i++) {
	     if(rowId== this.rowList[i].rowId){
		   this.rowList.splice(i,1);
		   break;
		 }
	  }
    },
	afteraddrow () {
      var i;
	  var rowId = this.menuRowId;

      for (i = 0; i < this.rowList.length; i++) {
	     if(rowId== this.rowList[i].rowId){
		   var row =[];  
		   row["rowId"]=this.uuid();
		   this.rowList.splice(i+1,0,row);
		   break;
		 }
	  }
	  console.log('afteraddrow rowId:'+rowId);
    },	
	editProperties(itemId){
	  debugger;
	  console.log('itemId:'+itemId);
	  //组装控件属性
	  var obj;
	  obj = this.findNowObj(itemId);
	  if(obj){
	     //输入框
		 if(obj.type==="input"){
		   //查找类型为input的属性模版
		   var tempObj;
		   tempObj = this.findPropertiesTemp(obj.type);
		   var cloneTempObj;
		   //克隆一个对象
		   cloneTempObj = JSON.parse(JSON.stringify(tempObj));
		   //填写cloneTempObj属性值
		   this.fillInputProperties(cloneTempObj,obj);
		   console.log('cloneTempObj:'+JSON.stringify(cloneTempObj));
		   this.editPropertyTemplate = cloneTempObj
		   //显示属性对话框
		   this.QualityDialogFlag =true;
		 }
	  }
	},
	//控件改变属性方法回调
	changedProperties(itemId,propertiesData){
	     debugger;
		 console.log('changedProperties:itemId:'+itemId+',propertiesData:'+propertiesData);
		  var obj;
	      obj = this.findNowObj(itemId);
	      if(obj){
		   //TODO:修改控件属性
			if(obj.type==='input'){
		     this.fillInputCtrlProperties(obj,propertiesData);
		   }
	      }
	},
	//填写输入框控件属性
	fillInputCtrlProperties(obj,propertiesData){
		if(propertiesData.modelname){
			obj.model =propertiesData.modelname;
		}
		if(propertiesData.title){
			obj.label =propertiesData.title;
		}
		if(propertiesData.width){
			obj.options.width =propertiesData.width;
		}
		if(propertiesData.placeholder){
			obj.options.placeholder =propertiesData.placeholder;
		}
		
	},
	//查询对应类型的模版
	findPropertiesTemp(type){
	   var i;
	   for(i=0;i<this.propertyTemplate.length;i++){
	      if(this.propertyTemplate[i].ctrlType===type){
			  return this.propertyTemplate[i];
		  }
	   }
	   return null;
	},
	//填写cloneTempObj属性值
	fillInputProperties(cloneTempObj,obj){
	    var i;
		cloneTempObj.id = obj.id;
	   for(i=0;i<cloneTempObj.ctrlProperties.length;i++){
	       if(cloneTempObj.ctrlProperties[i][0].model == "modelname"){
		     cloneTempObj.ctrlProperties[i][0].value = obj.model;
		   }else if(cloneTempObj.ctrlProperties[i][0].model =="title"){
			  cloneTempObj.ctrlProperties[i][0].value = obj.label;
		   }else if(cloneTempObj.ctrlProperties[i][0].model =="width"){
		      cloneTempObj.ctrlProperties[i][0].value = obj.options.width;
		   }else if(cloneTempObj.ctrlProperties[i][0].model =="placeholder"){
		     cloneTempObj.ctrlProperties[i][0].value = obj.options.placeholder;
		   }
	   }
	},
	//预览
	prevView(){
	    debugger;
		storage.set('prevctrl',this.rowList);
		this.$router.push({ path: "/prevView"});
	}
}
}
</script>
<style>
    .demo * {
        float: left;
        width: 100px;
        height: 100px;
        border: 1px solid #000;
    }
    img {
        width: 100px;
        height: 100px;
        display: inline-block;
    }
    .drop {
        width: 100px;
        height: 100px;
        border: 1px solid #000;
    }
.onerow {
  display: flex;
  margin-left:0px;
  width: 100%;
}
.list-group {
  display: flex;
  flex-direction: column;
  padding-left: 0;
  margin-bottom: 0;
  border: 0;
}
.list-group-item:first-child {
  border-top-left-radius: 0.25rem;
  border-top-right-radius: 0.25rem;
}
.list-group-item {
  position: relative;
  display: block;
  padding: 0.75rem 1.25rem;
  margin-bottom: -1px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  box-sizing: border-box;
}
.el-collapse-item__header {
  border: 0;
  height: 40px;
  line-height: 40px;
}
.el-collapse-item__wrap {
  border-bottom: 0;
}
.el-icon-circle-close {
    color: #c9a2a2;
    font-size: 20px;
    position:relative;
	margin-top:-20px;
    right: 50px;
}
.col-4 {
  flex: 0 0 70%;
  max-width: 70%;
  margin-right: 10px;
  margin-left:5px;
}
.col-5 {
  flex: 0 0 30%;
  max-width: 30%;
  margin-right: 2px;
}
.Grid {
  width: 100%;
}
.Row {
  display: flex;
  border: 1px dashed #000;
  height: 50px;
}
.Grid-cell {
  display: flex;
  /* flex: 1; */
}
.el-form-item__label {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.el-form-item__content {
  line-height: 40px;
  position: relative;
  font-size: 14px;
  pointer-events: none;
}	
</style>